package br.edu.ufcg.sig.client.panels;

import br.edu.ufcg.sig.client.services.DelictServices;
import br.edu.ufcg.sig.client.services.DelictServicesAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.event.MapClickHandler.MapClickEvent;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.maps.client.overlay.Overlay;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.SimpleStore;
import com.gwtext.client.data.Store;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.DateField;
import com.gwtext.client.widgets.form.Field;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.form.TextArea;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.form.TimeField;
import com.gwtext.client.widgets.form.event.ComboBoxCallback;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
import com.gwtext.client.widgets.layout.AnchorLayoutData;

public class CriminalFormPanel extends Panel{
	
	com.gwtext.client.widgets.Window window;
	
	private static final DelictServicesAsync DELICT_SERVICES = (DelictServicesAsync) GWT.create(DelictServices.class);

	public CriminalFormPanel(final com.gwtext.client.widgets.Window window, MapClickEvent event){
		super();
		this.window = window;
		makeComponents(event);
		
	}

	private void makeComponents(final MapClickEvent event) {
		final FormPanel formPanel = new FormPanel();  
		formPanel.setFrame(true);  
		formPanel.setWidth(350);  
		formPanel.setLabelWidth(75);  
		formPanel.setUrl("save-form.php");  

		Label label = new Label();  
		label.setHtml("<p>This is an example of a Form Label. This can have any <b>HTML</b> content.</p>");  
		label.setCls("simple-form-label");  
		label.setWidth(350);  
		label.setHeight(20);  

		int componentWidth = 190;
		
		 final Store store = new SimpleStore(new String[]{"crime"}, getCriminalTypes());  
		 store.load();  

		 final ComboBox delictType = new ComboBox();  
		 delictType.setForceSelection(true);  
		 delictType.setMinChars(1);  
		 delictType.setFieldLabel("Tipo de Crime: ");  
		 delictType.setStore(store);  
		 delictType.setDisplayField("crime");  
		 delictType.setMode(ComboBox.LOCAL);  
		 delictType.setTriggerAction(ComboBox.ALL);  
		 delictType.setEmptyText("Selecione o tipo de crime");  
		 delictType.setLoadingText("Carregando...");  
		 delictType.setTypeAhead(true);  
		 delictType.setSelectOnFocus(true);  
		 delictType.setWidth(componentWidth);  

		 delictType.setHideTrigger(false);  

		 delictType.addListener(new ComboBoxListenerAdapter() {  
			 public boolean doBeforeQuery(ComboBox comboBox, ComboBoxCallback cb) { return true; }  

			 public boolean doBeforeSelect(ComboBox comboBox, Record record, int index) {  
				 return super.doBeforeSelect(comboBox, record, index);  
			 }  
			 
			 public void onCollapse(ComboBox comboBox) { }  

			 public void onExpand(ComboBox comboBox) { }  

			 public void onSelect(ComboBox comboBox, Record record, int index) { }   

			 public void onBlur(Field field) { }  

			 public void onChange(Field field, Object newVal, Object oldVal) { }  

			 public void onFocus(Field field) { }  

			 public void onInvalid(Field field, String msg) {  
				 super.onInvalid(field, msg);  
			 }  

			 public void onSpecialKey(Field field, EventObject e) {  } 
			 
		 });  

		formPanel.add(delictType);
		
		final Store storeLocation = new SimpleStore(new String[]{"localidade"}, getLocationTypes());  
		storeLocation.load(); 
		final ComboBox locationType = new ComboBox();  
		locationType.setForceSelection(true);  
		locationType.setMinChars(1);  
		locationType.setFieldLabel("Tipo de Localidade: ");  
		locationType.setStore(storeLocation);  
		locationType.setDisplayField("localidade");  
		locationType.setMode(ComboBox.LOCAL);  
		locationType.setTriggerAction(ComboBox.ALL);  
		locationType.setEmptyText("Selecione o tipo de localidade");  
		locationType.setLoadingText("Carregando...");  
		locationType.setTypeAhead(true);  
		locationType.setSelectOnFocus(true);  
		locationType.setWidth(componentWidth);  

		locationType.setHideTrigger(false);  

		locationType.addListener(new ComboBoxListenerAdapter() {  
			public boolean doBeforeQuery(ComboBox comboBox, ComboBoxCallback cb) { return true; }  

			 public boolean doBeforeSelect(ComboBox comboBox, Record record, int index) {  
				 return super.doBeforeSelect(comboBox, record, index);  
			 }  
			 
			 public void onCollapse(ComboBox comboBox) { }  

			 public void onExpand(ComboBox comboBox) { }  

			 public void onSelect(ComboBox comboBox, Record record, int index) { }   

			 public void onBlur(Field field) { }  

			 public void onChange(Field field, Object newVal, Object oldVal) { }  

			 public void onFocus(Field field) { }  

			 public void onInvalid(Field field, String msg) {  
				 super.onInvalid(field, msg);  
			 }  

			 public void onSpecialKey(Field field, EventObject e) {  } 
		 });  

		formPanel.add(locationType);
	
		final DateField dateOfDelict = new DateField("Data da ocorrência:", "data", componentWidth);  
		dateOfDelict.setAllowBlank(false);
		formPanel.add(dateOfDelict);

		final TimeField time = new TimeField("Horário", "horarario", 190);  
		time.setMinValue("0:00");  
		time.setMaxValue("23:00");  
		formPanel.add(time);
		
		final TextField numVitims = new TextField("Quantidade de vítimas:", "qtdvitimas", componentWidth);  
		numVitims.setAllowBlank(false);  
		formPanel.add(numVitims);
		
		final TextField numRobbers = new TextField("Quantidade de criminosos:", "qtdcriminosos", componentWidth);  
		numRobbers.setAllowBlank(false);  
		formPanel.add(numRobbers);
		
		final TextArea description = new TextArea("Descrição:", "descricao");  
		description.setHideLabel(true);		
		// anchor width by percentage and height by raw adjustment  
		// sets width to 100% and height to "remainder" height - 53px  
		formPanel.add(description, new AnchorLayoutData("100% -200"));
		
//		Checkbox usedArmor = new Checkbox("Uso de arma?"); 
		
		final Store storeUsedArmor = new SimpleStore(new String[]{"arma"}, getGunsTypes());  
		storeLocation.load(); 
		final ComboBox usedArmor = new ComboBox();  
		usedArmor.setForceSelection(true);  
		usedArmor.setMinChars(1);  
		usedArmor.setFieldLabel("Tipo de Arma: ");  
		usedArmor.setStore(storeUsedArmor);  
		usedArmor.setDisplayField("arma");  
		usedArmor.setMode(ComboBox.LOCAL);  
		usedArmor.setTriggerAction(ComboBox.ALL);  
		usedArmor.setEmptyText("Selecione o tipo de arma");  
		usedArmor.setLoadingText("Carregando...");  
		usedArmor.setTypeAhead(true);  
		usedArmor.setSelectOnFocus(true);  
		usedArmor.setWidth(componentWidth);

		usedArmor.addListener(new ComboBoxListenerAdapter() {  
			public boolean doBeforeQuery(ComboBox comboBox, ComboBoxCallback cb) { return true; }  

			 public boolean doBeforeSelect(ComboBox comboBox, Record record, int index) {  
				 return super.doBeforeSelect(comboBox, record, index);  
			 }  
			 
			 public void onCollapse(ComboBox comboBox) { }  

			 public void onExpand(ComboBox comboBox) { }  

			 public void onSelect(ComboBox comboBox, Record record, int index) { }   

			 public void onBlur(Field field) { }  

			 public void onChange(Field field, Object newVal, Object oldVal) { }  

			 public void onFocus(Field field) { }  

			 public void onInvalid(Field field, String msg) {  
				 super.onInvalid(field, msg);  
			 }  

			 public void onSpecialKey(Field field, EventObject e) {  } 
		 });  
		
		formPanel.add(usedArmor);  

		Button save = new Button("Salvar");
		save.addListener(new ButtonListenerAdapter() {  
			public void onClick(Button button, EventObject e) {  
				
				DELICT_SERVICES.createDelict(delictType.getValue(), locationType.getValue(), dateOfDelict.getValue().toString(),
						time.getValue().toString(), description.getValueAsString(), usedArmor.getValue(),
						Integer.parseInt(numVitims.getValueAsString()), Integer.parseInt(numRobbers.getValueAsString()),
						coordinatesFormat(event.getLatLng()), new AsyncCallback<String>(){

					public void onFailure(Throwable caught) {
						Window.alert("Nao foi possivel adicionar o crime");
						caught.printStackTrace();
						
					}

					public void onSuccess(String result) {
						MapWidget sender = event.getSender();
						Overlay overlay = event.getOverlay();
						LatLng point = event.getLatLng();

						if (overlay != null && overlay instanceof Marker) {
							sender.removeOverlay(overlay);
						} else {
							sender.addOverlay(new Marker(point));
						} 
						
					}
					
				});
				window.close();
			}

			private String coordinatesFormat(LatLng latLng) {
				return latLng.getLatitude() + " " + latLng.getLongitude();				
			}			
		});  
		formPanel.addButton(save);  

		Button cancel = new Button("Cancelar");  
		cancel.addListener(new ButtonListenerAdapter() {  
			public void onClick(Button button, EventObject e) {  
				window.close();  
			}  
		});  
		
		
		formPanel.addButton(cancel);  

		this.add(formPanel);  
		
	}

	private Object[][] getCriminalTypes() {
		return new String[][]{  
				new String[]{"Roubo"},  
				new String[]{"Furto"},  
				new String[]{"Tentativa de roubo",},  
				new String[]{"Tentativa de furto"}  
		};  
	}
	
	private Object[][] getLocationTypes() {
		return new String[][]{  
				new String[]{"Via Pública"},  
				new String[]{"Transporte Coletivo"},  
				new String[]{"Estabelecimento Comercial",},  
				new String[]{"Residência"},
				new String[]{"Escola",},
				new String[]{"Praça Pública",},
				new String[]{"Outros"}
		};  
	}
	
	private Object[][] getGunsTypes() {
		return new String[][]{  
				new String[]{"Nenhuma"},  
				new String[]{"Branca"},  
				new String[]{"Fogo",}				
		};  
	}

}
